<template>
  <global-layout @dynamicRouterShow="dynamicRouterShow" @reloadPortlet="reloadPortlet">
    <contextmenu :itemList="menuItemList" :visible.sync="menuVisible" style="z-index: 9999;" @select="onMenuSelect"/>
    <!-- 原有的： v-if="multipage && activePage !== '/index/portal'" -->
    <!--
      activePage !== indexKey  不显示首页
      十大功能的路由跳转为自己的工作台

    -->
    <a-tabs
      v-if="activePage !== INDEX_MAIN_PAGE_PATH"
      :active-key="activePage"
      class="labelPage"
      @change="changePage"
      @tabClick="tabCallBack"
      type="card">

      <a-tab-pane v-for="(item, index) in pageList" :key="item.fullPath" v-if="item.meta.title !== '首页' &&  item.fullPath !== INDEX_MAIN_PAGE_PATH">
        <template slot="tab">
          <span v-if="item.meta.icon && item.meta.icon.indexOf('spcy-icon') !== -1" style="display: inline-block;font-size: 14px;height: 34px;" :class="'iconfont '+item.meta.icon"></span>
          <span
            @contextmenu.prevent="onContextmenu($event, index)"
            :title="item.meta.title">
            <ych-icon :type="item.meta.icon"></ych-icon>
            <!-- <a-icon :type="item.meta.icon" /> -->
            {{ item.meta.title }}
          </span>
          <a-icon
            v-if="item.fullPath !== indexKey && item.meta.title !== currentModulemenuData.childrenTitle"
            type="close"
            style=" position: relative; top: -11px;padding-left: 5px;"
            @click.stop="remove(item.fullPath)"
          />
        </template>
      </a-tab-pane>

    </a-tabs>
    <transition name="page-toggle">
      <!-- 内容部分 -->
        <a-spin size="large" :spinning="spinningPrice">
          <!-- :style="{height: activePage !== '/index/portal'? 'calc(100vh - 150px)' : 'calc(100vh - 80px)'}" -->
          <div :style="{height:activePage == '/index/portal'?'calc(100vh - 134px)':'calc(100vh - 110px)'}"  class="main">
            <keep-alive>
              <router-view v-if="isRouterAlive" :key="$route.fullPath" ref="page"/>
            </keep-alive>
            <!-- :is="iframe.meta.componentName" -->
            <component
              v-for="iframe in iframeKeepAlives"
              :key="iframe.fullPath"
              :meta="iframe.meta"
              :is="iframe.meta.componentName"
              v-show="iframe.fullPath === $route.fullPath"
            ></component>
          </div>
        </a-spin>
    </transition>
    <!-- 审评员进来需要全局弹窗提示让审评员添加签名和银行卡号 -->
    <verifyByYkhQzdmTx ref="verifyByYkhQzdmTxRef" />
  </global-layout>
</template>

<script>
  import Vue from 'vue'
  import VueRouter from 'vue-router'
  import GlobalLayout from './GlobalLayout'
  import Contextmenu from '../menu/Contextmenu'
  import { mixin, mixinDevice } from '@/utils/mixin.js'
  import { triggerWindowResizeEvent } from '@/utils/util'
  import { INDEX_MAIN_PAGE_PATH } from '@/store/mutation-types'
  import {randomString} from '../../utils/util'
  import { mapState, mapActions ,mapGetters} from 'vuex'
  import store from '../../store'
  import verifyByYkhQzdmTx from '@/components/verifyByYkhQzdmTx/verifyByYkhQzdmTx.vue'
  
  const indexKey = INDEX_MAIN_PAGE_PATH

  export default {
    name: 'TabLayout',
    components: {
      GlobalLayout,
      Contextmenu,
      verifyByYkhQzdmTx,
    },
    mixins: [mixin, mixinDevice],
    data() {
      return {
        indexKey: indexKey,
        INDEX_MAIN_PAGE_PATH:INDEX_MAIN_PAGE_PATH,
        pageList: [],
        pagekey: null, // 右键页签
        linkList: [],
        activePage: '',
        menuVisible: false,
        menuItemList: [
          { key: '4', icon: 'reload', text: this.$t('m.common.button.refresh')},
          { key: '1', icon: 'arrow-left', text: this.$t('m.common.button.close_left') },
          { key: '2', icon: 'arrow-right', text: this.$t('m.common.button.close_right') },
          { key: '3', icon: 'close', text: this.$t('m.common.button.close_other') }
        ],
        isRouterAlive: true,
        initialData: {}
        
      }
    },
    provide(){
      return{
        closeCurrent:this.closeCurrent,
        addRouter: this.addRouter,
        removeCache: this.removeCache,
      }
    },
    computed: {
      ...mapState({
        currentModulemenuData: state => state.user.currentModulemenuObj,
        isRewriteGlobalTabs: state => state.user.rewriteGlobalTabs,
        onlyCurrentPathData: state => state.user.onlyCurrentPath,
      }),
      spinningPrice(){
        return this.$store.state.permission.spinningPrice
      },
      iframeKeepAlives(){
        return this.$store.state.permission.iframeKeepAlives
      },
      keepAlives(){
        return this.$store.state.permission.keepAlives
      },
      tempRouterFullPath(){
        return this.$store.state.permission.tempRouterFullPath
      },
      multipage() {
        //判断如果是手机模式，自动切换为单页面模式
        if (this.isMobile()) {
          return false
        } else {
          return this.$store.state.app.multipage
        }
      },
      currentRemoveMenu(){
        return this.$store.state.permission.currentRemoveMenu
      }
    },
    mounted() {
      // 如果需要通过refs来访问组件实例并初始化数据
      //console.log('我在拿全局路由',this.pageList)
      this.$nextTick(() => {
        setTimeout(()=>{
          //console.log('我在拿全局路由',this.$refs.page)
          // this.$refs.page.initDataMountedData()
        },500)
      });
    },
    created() {
      this.$nextTick(()=>{
        setTimeout(()=>{
          this.$refs.verifyByYkhQzdmTxRef.getData()
          // this.$refs.tablayoutComponentRef.initDataCreatedData()
        },200)
      })
      
      if (this.$route.path !== (this.onlyCurrentPathData || indexKey)) {
        this.addIndexToFirst()
      }
      if(this.$route.path !== '/index/portal' &&this.currentModulemenuData.childrenFirstPath && this.$route.path !== this.currentModulemenuData.childrenFirstPath){
        this.addIndexToSecond()
      }
      let storeKey = 'route:title:' + this.$route.fullPath
      let routeTitle = this.$ls.get(storeKey)
      if (routeTitle) {
        this.$route.meta.title = routeTitle
      }
      this.pageList.push(this.$route)
      //console.log('路由有什么啊',this.pageList)
      this.$store.commit("SET_KEEPALIVES", this.pageList)
      this.$store.dispatch("UpdateCurrentRouteName", this.$route.fullPath)
      this.linkList.push(this.$route.fullPath)
      this.activePage = this.$route.fullPath

      Vue.prototype.dynamicRouterShow = this.dynamicRouterShow;
      Vue.prototype.getLinkList = this.getLinkList;
      //console.log('当前的getLinkList',this.getLinkList)
    },
    watch: {
      '$route': function(newRoute, oldRoute) {
        //console.log(newRoute,'"新的路由----------newRoute-----------------------------');
        //console.log(oldRoute,'"新的路由----------newRoute-----------------------------');
        //通过#的不跳转页面
        if(newRoute.fullPath.indexOf("#") !== -1){
          return;
        }
        
        //console.log("$route新的路由",newRoute)
        //console.log("新的路由",this.pageList)
        let newRouteData = newRoute
        //console.log('不需要清空路由吗？',this.isRewriteGlobalTabs,indexKey,this.onlyCurrentPathData,(this.onlyCurrentPathData || indexKey),this.currentModulemenuData)
        //console.log("新的路由8888",this.pageList)
        // (newRoute.fullPath == indexKey?indexKey:(this.onlyCurrentPathData?this.onlyCurrentPathData:indexKey))
        let arr = this.pageList.filter(item=>item.fullPath == newRoute.fullPath)
        //console.log("新的路由8888",arr)
        //console.log('我原来有什么？',this.$route)
        if((this.isRewriteGlobalTabs && !arr.length) ){
          
          let routerArr = newRoute.fullPath == this.onlyCurrentPathData
          if(!routerArr){
            this.pageList = [{
              name: this.onlyCurrentPathData?this.currentModulemenuData.childrenName:'index-portal',
              path: (this.onlyCurrentPathData || indexKey),
              fullPath: (this.onlyCurrentPathData || indexKey),
              meta: {
                icon: 'home',
                title: this.onlyCurrentPathData && this.onlyCurrentPathData !== indexKey ?this.currentModulemenuData.childrenTitle:this.$t('m.system.permission.other.menu_workbench')
              }
            },this.$route]//,this.$route
          }else{
            this.pageList = [this.$route]
          }
          
          this.linkList = [(this.onlyCurrentPathData || indexKey),newRoute.fullPath]
          
            //console.log("新的路由8888",this.pageList)
            // newRouteData.matched = [newRoute.matched[0],newRoute.matched[1]]
            // this.addIndexToFirst()
            // this.addIndexToSecond()
            this.$store.commit('SET_REWRITEGLOBALTABS', false)
          }else{
            this.$store.commit('SET_REWRITEGLOBALTABS', false)
          }
          this.activePage = newRoute.fullPath
        //console.log('判断如果是手机模式，自动切换为单页面模式',this.multipage)
        if (!this.multipage) {//手机模式
          this.linkList = [newRoute.fullPath]
          this.pageList = [Object.assign({},newRoute)]
          this.$store.commit("SET_KEEPALIVES", this.pageList)
        } else if((this.onlyCurrentPathData || indexKey) === newRoute.fullPath) {

        }else if (this.linkList.indexOf(newRoute.fullPath) < 0) {
          this.linkList.push(newRoute.fullPath)
          this.pageList.push(Object.assign({},newRoute))
          this.$store.commit("SET_KEEPALIVES", this.pageList)
        } else if (this.linkList.indexOf(newRoute.fullPath) >= 0) {
            let oldIndex = this.linkList.indexOf(newRoute.fullPath)
            let oldPositionRoute = this.pageList[oldIndex]
            //console.log('-------oldPositionRoute',oldPositionRoute)
            this.pageList.splice(oldIndex, 1, Object.assign({},newRoute,{meta:oldPositionRoute.meta}))
            this.$store.commit("SET_KEEPALIVES", this.pageList)
        } else if(newRoute.meta.isIframe && !newRoute.meta.keepAlive){
          this.$store.commit("SET_KEEPALIVES", this.pageList)
        }

        if(oldRoute && !oldRoute.meta.keepAlive){
          this.removeCache(oldRoute.fullPath)
        }
      },
      'activePage': function(key) {
        //console.log('activePage',key)
        //console.log('activePage',this.linkList)
        //console.log('activePage----pageList',this.pageList)
        let index = this.linkList.lastIndexOf(key)
        //console.log('activePage----pageList',index,this.pageList)
        //console.log('activePage----pageList',index,this.linkList)
        let waitRouter = this.pageList[index]
        this.$router.push(Object.assign({},waitRouter)).catch(err => {});
        this.changeTitle(waitRouter.meta.title)
      },

      'multipage': function(newVal) {
        if (!newVal) {
          this.linkList = [this.$route.fullPath]
          this.pageList = [this.$route]
          this.$store.commit("SET_KEEPALIVES", this.pageList)
        }
      },
      device() {
        if (this.multipage && this.linkList.indexOf((this.onlyCurrentPathData || indexKey)) === -1) {
          this.addIndexToFirst()
        }
      },
      keepAlives(newVal, oldVal) {
        const removeVal = oldVal.filter(item => newVal.indexOf(item) === -1);
        removeVal.forEach(item => {
          this.removeCache(item)
        })
      },
      tempRouterFullPath(newVal, oldVal) {
        // 还有问题未解决
        // const removeVal = oldVal.filter(item => newVal.indexOf(item) === -1);
        // if (removeVal.length > 0) {
        //   // 删掉动态路由，官方暂不支持，此为替代方案
        //   // 获取原始路由数据配置
        //   const options = this.$router.options
        //
        //   // 用原始数据重新 new 一个路由
        //   const _VueRouter = new VueRouter(options)
        //
        //   // 用新路由的 matcher 替换旧路由的 matcher
        //   this.$router.matcher = _VueRouter.matcher
        //
        //   // 还原路由规则
        //   this.$store.getters.addRouters.forEach(routeItem => {
        //     this.$router.addRoute(routeItem)
        //   })
        //   this.$store.state.permission.tempRouters.forEach(routeItem => {
        //     this.$router.addRoute(routeItem)
        //   })
        // }
      },
      'currentRemoveMenu': function(newVal, oldVal){//删除标签页
        if(newVal){
          this.remove(newVal)
        }
      }
    },
    methods: {
      addRouter(router, isNew) {
        //console.log('当前添加路由000000000000',router,isNew)
        if (isNew) {
          router.path = router.path + "/" + randomString(8)
        }
        router.path = '/tempRouter' + router.path
        const rootPath = router.path + '/index'
        const oldRouter = this.$router.getRoutes().find(item => item.path === rootPath)
        if (oldRouter) {
          return router.path
        }
        router.meta.tempRouter = true
        router.meta.keepAlive = true
        router.meta.parentFullPath = this.$route.fullPath
        router.meta.rootPath = rootPath
        const indexRouter = {
          path: rootPath,
          component: resolve => require(['@/framework/defaultPortal/TabLayout'], resolve),
          children: [router]
        }
        this.$router.addRoute(indexRouter)
        this.$store.commit("ADD_TEMPROUTER", indexRouter)
        return router.path
      },
      getLinkList(){
        return this.linkList;
      },
      // 将首页添加到第一位
      addIndexToFirst() {
        this.pageList.splice(0, 0, {
          name: 'index-portal',
          path: (this.onlyCurrentPathData || indexKey),
          fullPath: (this.onlyCurrentPathData || indexKey),
          meta: {
            icon: 'home',
            title: this.$t('m.system.permission.other.menu_workbench')
          }
        })
        this.$store.commit("SET_KEEPALIVES", this.pageList)
        this.linkList.splice(0, 0, (this.onlyCurrentPathData || (this.onlyCurrentPathData || indexKey)))
      },
      addIndexToSecond(){
        //console.log('我添加了固定路由',this.currentModulemenuData.childrenFirstPath)
        //console.log(this.pageList)
        this.pageList.splice(1, 0, {
          name: this.currentModulemenuData.childrenName,
          path: this.currentModulemenuData.childrenFirstPath,
          fullPath: this.currentModulemenuData.childrenFirstPath,
          meta: {
            icon: 'home',
            title: this.currentModulemenuData.childrenTitle
          }
        })
        this.$store.commit("SET_KEEPALIVES", this.pageList)
        this.linkList.splice(1, 0, this.currentModulemenuData.childrenFirstPath)
      },
      changeTitle(title) {
        let projectTitle = window._CONFIG.full_name || this.$t('m.logo.full_name')
        // 首页特殊处理
        if (this.$route.path === (this.onlyCurrentPathData || indexKey)) {
          document.title = projectTitle
        } else {
          document.title = title + ' · ' + projectTitle
        }
      },

      changePage(key) {
        this.activePage = key
      },
      tabCallBack() {
        this.$nextTick(() => {
          triggerWindowResizeEvent()
        })
      },
      remove(key) {
        if (key === (this.onlyCurrentPathData || indexKey)) {
          this.messageUtil.warning('首页不能关闭!')
          return
        }
        if (this.pageList.length === 1) {
          this.messageUtil.warning('这是最后一页，不能再关闭了啦')
          return
        }
        this.pageList = this.pageList.filter(item => item.fullPath !== key)
        this.$store.commit("SET_KEEPALIVES", this.pageList)
        let index = this.linkList.indexOf(key)
        this.linkList = this.linkList.filter(item => item !== key)
        index = index >= this.linkList.length ? this.linkList.length - 1 : index
        this.activePage = this.linkList[index]
        this.$store.commit("SET_REMOVEMENU",'')
      },
      onContextmenu(e, index) {
        this.pagekey = this.pageList[index].fullPath
        if (this.pagekey !== null) {
          e.preventDefault()
          this.menuVisible = true
        }
      },
      onMenuSelect(key, target) {
        let pageKey = this.pagekey
        switch (key) {
          case '1':
            this.closeLeft(pageKey)
            break
          case '2':
            this.closeRight(pageKey)
            break
          case '3':
            this.closeOthers(pageKey)
            break
          case '4':
            this.routeReload(pageKey)
            break
          default:
            break
        }
      },
      closeCurrent(){
        this.remove(this.activePage);
      },
      closeOthers(pageKey) {
        let index = this.linkList.indexOf(pageKey)
        if (pageKey === (this.onlyCurrentPathData || indexKey) || pageKey.indexOf('?ticke=')>=0) {
          this.linkList = this.linkList.slice(index, index + 1)
          this.pageList = this.pageList.slice(index, index + 1)
          this.$store.commit("SET_KEEPALIVES", this.pageList)
          this.activePage = this.linkList[0]
        } else {
          let indexContent = this.pageList.slice(0, 1)[0]
          this.linkList = this.linkList.slice(index, index + 1)
          this.pageList = this.pageList.slice(index, index + 1)
          this.linkList.unshift(indexContent.fullPath)
          this.pageList.unshift(indexContent)
          this.$store.commit("SET_KEEPALIVES", this.pageList)
          this.activePage = this.linkList[1]
        }
      },
      closeLeft(pageKey) {//删除左边菜单
        //console.log('删除左边菜单',pageKey)
        if (pageKey === (this.onlyCurrentPathData || indexKey)) {
          return
        }
        let tempList = [...this.pageList]
        let indexContent = tempList.slice(0, 1)[0]
        let indexContent2 = tempList.slice(1, 2)[0]
        //console.log('indexContent2',indexContent2)
        let index = this.linkList.indexOf(pageKey)
        this.linkList = this.linkList.slice(index)
        this.pageList = this.pageList.slice(index)
        this.linkList.unshift(indexContent2.fullPath)
        this.pageList.unshift(indexContent2)
        this.linkList.unshift(indexContent.fullPath)
        this.pageList.unshift(indexContent)
        this.$store.commit("SET_KEEPALIVES", this.pageList)
        if (this.linkList.indexOf(this.activePage) < 0) {
          this.activePage = this.linkList[0]
        }
      },
      closeRight(pageKey) {
        let index = this.linkList.indexOf(pageKey)
        this.linkList = this.linkList.slice(0, index + 1)
        this.pageList = this.pageList.slice(0, index + 1)
        this.$store.commit("SET_KEEPALIVES", this.pageList)
        if (this.linkList.indexOf(this.activePage < 0)) {
          this.activePage = this.linkList[this.linkList.length - 1]
        }
      },
      dynamicRouterShow(key,title){

        let keyIndex = this.linkList.indexOf(key)
        //console.log('菜单啊@@@@@@@@@@',key,title,this.linkList,this.pageList)
        debugger
        if(keyIndex>=0){
          let currRouter = this.pageList[keyIndex]
          let meta = Object.assign({},currRouter.meta,{title:title})
          this.pageList.splice(keyIndex, 1, Object.assign({},currRouter,{meta:meta}))
          this.$store.commit("SET_KEEPALIVES", this.pageList)
          if (key === this.activePage) {
            this.changeTitle(title)
          }
        }
      },

      routeReload(pageKey) {
        // 清除缓存
        let indexFullPath = this.linkList.indexOf(pageKey)
        let fullPath = this.pageList[indexFullPath].fullPath;

        this.removeCache(fullPath)

        this.isRouterAlive = false;

        this.$nextTick(() => {
          this.isRouterAlive = true;
          this.$store.commit("SET_KEEPALIVES", this.pageList)
        })
      },
      removeCache(fullPath){
        if (this.$refs.page) {
          const {
            cache, keys
          } = this.$refs.page.$vnode.parent.componentInstance
          if (cache[fullPath]) {
            delete cache[fullPath]
          }

          const index = keys.indexOf(fullPath)
          if (index > -1) {
            keys.splice(index, 1)
          }
        }
        this.$store.commit("REMOVE_IFRAMEKEEPALIVES", fullPath)
      },
      reloadPortlet(){
        this.routeReload((this.onlyCurrentPathData || indexKey))
      },

      
    }
  }
</script>

<style lang="less">

/* 主题标签页高度 */
@theme-tab-height: 36px;
@theme-tab-height-2: 36px;
// 定义字体大小
@theme-con-font-12: 12px;

.labelPage {
  height: @theme-tab-height;
  // border-bottom:1px solid #e8e8e8;
  position: relative;
  z-index: 10;
  background: #f0f2f5;
  margin: 0 8px;
  .ant-tabs {
    height: 40px;
  }
  .ant-btn {
    border: none;
    background: none;
    font-size: @theme-con-font-12;
    float: left;
    line-height: @theme-tab-height;
    color: #888;
    padding-left: 30px;
    overflow: hidden;
  }
  .ant-tabs-bar {
    margin: 0;
    border: none;
  }
  .ant-tabs-nav-wrap{
    margin: 0;
  }
  .ant-tabs-nav .ant-tabs-tab:first-child {
    padding: 0 11px ;
    border-left:1px solid #e8e8e8 ;
    .anticon-home{
      font-size: 14px;
      margin-right: 4px;
    }
    .close-icon{
      display: none;
    }
  }
  .ant-tabs-nav .ant-tabs-tab {
    font-size: 14px;
    height: @theme-tab-height;
    padding: 0 4px 0 16px;
    border: 0;
    margin: 0;
    color: #888;
    vertical-align: top;
    transition:none;
    border-right:1px solid #e8e8e8 ;
    // box-shadow: rgba(62, 57, 107, 0.1) 0 2px 6px 0;
    &.ant-tabs-tab-active{
      font-weight: normal;
      background: #e8edf7;
    }
    span {
      //   限制标签页最大宽度 溢出变省略号
      display: inline-block;
      max-width: 112px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      line-height: @theme-tab-height-2;
    }
    .close-icon {
      position: absolute;
      top: 13px;
      right: 10px;
      opacity: 1 !important;
      color: #8594aa;
      margin-right: 4px;
    }
    .close-icon:hover{
      color: red;
    }
  }
  .ant-tabs-ink-bar {
    height: 4px;
    display: none !important;
  }
  .ant-tabs-tab-prev.ant-tabs-tab-arrow-show,
  .ant-tabs-tab-next.ant-tabs-tab-arrow-show{
    width: 36px;
  }
  .ant-tabs-nav-container-scrolling{
    padding-right: 36px;
    padding-left: 36px;
  }
  .ant-tabs.ant-tabs-card > .ant-tabs-bar .ant-tabs-tab-active {
    font-weight: normal;
    border: 0;
  }
  .anticon{
    margin: 0 !important;
  }
}

</style>
